import { createWriteStream, existsSync, mkdirSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import type { FastifyInstance } from 'fastify';
import oneLineLogger from '@fastify/one-line-logger';
import DailyRotateFile from 'winston-daily-rotate-file';
import winston from 'winston';

import { env } from '../utils/env';

// 获取当前模块路径（ESM 替代方案）
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const logDir = join(__dirname, '../../logs');

// 确保日志目录存在 [1,3](@ref)
function ensureLogDir() {
  if (!existsSync(logDir)) {
    mkdirSync(logDir, { recursive: true }); // 递归创建缺失目录
  }
}

// 配置日志格式（添加时间戳）
const jsonFormat = winston.format.combine(
  winston.format.timestamp(), // 添加时间戳字段
  winston.format.json() // 输出为 JSON
);

// 配置每日日志轮转
const rotateTransport = new DailyRotateFile({
    filename: join(logDir, 'app-%DATE%.log'),
    datePattern: 'YYYY-MM-DD', // 按天分割
    zippedArchive: true,        // 压缩旧日志
    maxFiles: `${env.LOG_RETENTION}d`, // 保留天数
    maxSize: '20m',            // 单文件最大20MB
    utc: true,                  // 使用UTC时间确保00:00切割
    format: jsonFormat,
    auditFile: join(logDir, 'audit.json')
  });

export const logger = winston.createLogger({
  level: env.LOG_LEVEL,
  format: jsonFormat,
  transports: [rotateTransport]
});

export default (fastify: FastifyInstance) => {
  // 确保日志目录存在
  ensureLogDir();

  // 创建日志流（指向轮转系统）
  const logStream = rotateTransport.logStream;

  // 注册日志插件
  fastify.register(oneLineLogger, {
    stream: logStream,
    format: '{time} [{level}] {msg}',
    transport: { 
      colorize: false 
    }
  });

  rotateTransport.on('error', (err) => {
    console.error('日志写入失败', err);
  });

  const logger = winston.createLogger({
    transports: [rotateTransport]
  });

  fastify.log = logger as any; 

  // 添加启动日志
  logger.info('Logger initialized with daily rotation');
};